/**
 * @author Juntalis
 */
function SettingsManager() {
	// Database variables.
	var _db = null;
	
	// Read the settings from db.
	function _onDatabaseOpen(e) {
		Settings.__load(_db, App.onSettingsLoaded);
	}
	
	// Save the settings before closing.
	function _onWindowClose() {
		Settings.__save();
	}
	
	// Our public functions.
	return {
		SetUser : function(usr, pswd) {
			// Makes it easier to set the user name
			// and password.
			if (usr) Settings.User.Name = usr;
			if (pswd) Settings.User.Password = pswd;
		},
		
		LoadSettings : function(dbFile) {
			// The settings database in the app directory
			// Add handler to save the settings
			window.nativeWindow.addEventListener("closing", _onWindowClose);
			// Open connection to settings.db database
			_db = new air.SQLConnection();
			_db.addEventListener(air.SQLEvent.OPEN, _onDatabaseOpen);
			_db.open(dbFile, air.SQLMode.CREATE);
		},
		
		SaveSettings : function() {
			Settings.__save()
		},
		
		CreateSettings: function(dbSettings) {
			var conn = new air.SQLConnection();
			var blFail = false; var blDone = false;
			var stmt = new air.SQLStatement();
			var iQuery = 0;

			// Queries
			var arrQueries =
			[
				["Remember", "User", "false"],
				["AutoLogin", "User", "false"],
				["Name", "User", ""],
				["Password", "User", ""],
				["RecentBot", "App", ""],
				["RecentServer", "App", ""]
			];
			
			conn.open( dbSettings, air.SQLMode.CREATE );
			stmt.sqlConnection = conn;
			stmt.text =
				"CREATE TABLE AppSettings ("+
					"IdSetting INTEGER  NOT NULL PRIMARY KEY AUTOINCREMENT,"+
					"Name TEXT  UNIQUE NOT NULL,"+
					"Namespace TEXT  NULL,"+
					"Value TEXT  NULL"+
				");"
			while ((!blFail) && (!blDone)) {
				try {
					stmt.execute();
				} catch (e) {
					blFail = true;
				}
				
				if (iQuery == 6) blDone = true;
				
				if ((!blFail)&&(!blDone)) {
					stmt.text = "INSERT INTO AppSettings VALUES ( ?, ?, ?, ? )";
					stmt.parameters[0] = null;
					stmt.parameters[1] = arrQueries[iQuery][0];
					stmt.parameters[2] = arrQueries[iQuery][1];
					stmt.parameters[3] = arrQueries[iQuery][2];
					iQuery++;
				}
			}
			
			if(blFail) {
				alert("There was an error building a new AppSettings database!");
				App.Exit();
			}
			
		}
	};
}

//"static" class to handle our app settings
var Settings = {
	//some static properties to hold db connection and the inital state
	__db: null,
	__result: null,
	
	//this method will load the settings from the db
	__load: function(dbconn,callb) {
		Settings.__db = dbconn;
		
		//execute simple select * on the settings table
		var stmt = new air.SQLStatement();
			stmt.sqlConnection = dbconn;
			stmt.text = "select IdSetting, Name, Value, Namespace from AppSettings";
			stmt.execute();
		
		var result = stmt.getResult().data;

		//save the settings in the class property __result
		Settings.__result = result;
		
		//cycle trough the db result and make properties into the class itself
		for( var i=0; i<result.length; i++ ){

			//if the property has namespace create one for it
			if (result[i].Namespace!=null) {
				//fetch setting property with namespace
				if (!Settings[result[i].Namespace]) {
					Settings[result[i].Namespace] = {};
				}
				Settings[result[i].Namespace][result[i].Name] = result[i].Value;
			} else {
				//a plain setting property - create it directly in the class
				Settings[result[i].Name] = result[i].Value;
			}
		}
		//make sure we don't cause memory leaks
		stmt = null;
		result = null;
		
		// hit the callback
		if(callb)
			callb();
	},
	
	//this method will save all changed settings
	__save: function() {
		var stmt = new air.SQLStatement();
			stmt.sqlConnection = Settings.__db;
		
		//walk trough all settings INITALLY loaded from the database
		for (var i = 0; i < Settings.__result.length; i++) {
			
			//check if the current property has namespace
			if (Settings.__result[i].Namespace!=null) {
				//check if the initial value is equal to the current value
				if ( Settings[Settings.__result[i].Namespace][Settings.__result[i].Name] != Settings.__result[i].Value ) {
					//update the db. bound parameters are always better
					stmt.text = "UPDATE AppSettings SET Value= :value where Name= :name and Namespace= :namespace";
					stmt.parameters[":name"] = Settings.__result[i].Name;
					stmt.parameters[":value"] = Settings[Settings.__result[i].Namespace][Settings.__result[i].Name];
					stmt.parameters[":namespace"] = Settings.__result[i].Namespace;
					stmt.execute();
				}
			}
			 else {
				//check if the initial value is equal to the current value
				if (Settings[Settings.__result[i].Name] != Settings.__result[i].Value) {
					//update the db, look for namespace equals NULL
					stmt.text = "UPDATE AppSettings SET Value= :value WHERE Name= :name and Namespace IS NULL";
					stmt.parameters[":name"] = Settings.__result[i].Name;
					stmt.parameters[":value"] = Settings[Settings.__result[i].Name];
					stmt.execute();
				}
				
			}
			
			
		}
		stmt = null;
	}
};